package 链表算法题;

public class 两数相加 {
    public class ListNode{
        int val;
        ListNode next;
        ListNode(int x){val = x;}
    }
    public ListNode addTwoNumbers(ListNode l1,ListNode l2){
        ListNode dummyHead  = new ListNode(0);
        ListNode p = l1;ListNode q = l2; ListNode curr = dummyHead;
        //carry表示进位
        int carry = 0;
        while(p!=null || q!=null){
            int x = (p!=null)?p.val:0;
            int y = (q!=null)?q.val:0;
            int sum = carry+x+y;
            //进位数
            carry = sum/10;
            //新节点的数值
            curr.next = new ListNode(sum%10);
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        //这里保证的是如果最后一位都还有进位的话 真就又直接创建一个节点
        if (carry>0){
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;

    }
}
